<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | 租户数据控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\model\DepartmentModel;
use common\service\TenantService;
use common\validate\Tenant;
use support\ErrorCode;
use think\Exception;
use think\Request;
use think\Tree;

class TenantController extends VerifyController
{
    /**
     * @var \common\service\TenantService
     */
    protected $tenantService;

    public function __construct()
    {
        parent::__construct();
        $this->tenantService = new TenantService();
    }

    /**
     * 获取租户列表
     * @param Request $request
     * @return \think\Response
     */
    public function select(Request $request)
    {
        $param = $request->param();
        $resParam = [];
        if (array_key_exists('param', $param)) {
            $resParam = $param['param'];
        }
        $resData = $this->tenantService->select($resParam);
        return json(success_response('Get tenant list successfully.', $resData));
    }

    /**
     * 审核通过---的租户列表
     */
    public function selectApprovedTenant(Request $request)
    {
        $param = $request->param()['param'];
        $page = $request->param()['param']['page'] ?? [1, 50];

        $resData = $this->tenantService->selectApprovedTenant($param, $page);

        return json(success_response('Get tenant list successfully.', $resData));
    }

    /**
     * 查询当前用户所有租户列表
     * @param Request $request
     * @return \think\Response
     */
    public function selectCurrentUserTenant(Request $request)
    {
        $resData = $this->tenantService->selectCurrentUserTenant($request->getUserId());
        return json(success_response('', $resData));
    }

    /**
     * 切换租户激活状态
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function switchStatus(Request $request)
    {
        $param = $request->param();
        $resData = $this->tenantService->switchStatus($param['param']);
        return json(success_response('Successfully switched tenant status.', $resData));
    }

    /**
     * 获取指定一个租户下所有部门
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function getDepartmentTree(Request $request)
    {
        $param = $request->param();
        $resData = $this->tenantService->getDepartmentTree($param['param']);
        return json(success_response('Get all department tree of current tenant successfully.', $resData));
    }

    /**
     * 邀请成员加入部门
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function joinDepartment(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->tenantService->joinDepartment($param['data']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取租户部门成员
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function selectDepartmentUser(Request $request)
    {
        $param = $request->param();
        if (!isset($param['param']['filter']['tenant_id']) || $param['param']['filter']['tenant_id'] <= 0) {
            $param['param']['filter']['tenant_id'] = $request->getTenantId();
        }
        $includeEmployed = $param['param']['include_employed'] ?? 'no';
        $resData = $this->tenantService->selectDepartmentUser($param['param'], $includeEmployed === 'yes');
        return json(success_response('', $resData));
    }

    /**
     * 移除租户部门成员
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function deleteDepartmentUser(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->tenantService->deleteDepartmentUser($param['param']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 批量设置角色
     * @param Request $request
     * @return \think\Response
     * @deprecated 2023年5月19日 角色权限拆分了
     */
    public function saveRole(Request $request)
    {
        try {
            $resData = $this->tenantService->saveRole($request->param());
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 批量设置部门
     * @param Request $request
     * @return \think\Response
     * @deprecated 2023年5月19日
     */
    public function saveDept(Request $request)
    {
        try {
            $resData = $this->tenantService->saveDept($request->param());
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询当前租户下的用户列表
     * @param Request $request
     * @return \think\Response
     */
    public function selectTenantUser(Request $request): \think\Response
    {
        try {
            $param = $request->param();
            $includeEmployed = $param['param']['include_employed'] ?? 'no';
            $reData = $this->tenantService->selectTenantUser($request->getTenantId(), $param, $includeEmployed === 'yes');
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 用户切换到指定租户
     * @param Request $request
     * @return \think\Response
     */
    public function switchToTenant(Request $request)
    {
        try {
            $param = $request->param();
            $reData = $this->tenantService->switchToTenant($request->getUserId(), $param['param']);
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询当前用户申请的租户
     * @param Request $request
     * @return \think\Response
     */
    public function getUserTenantApply(Request $request)
    {
        try {
            $reData = $this->tenantService->getUserTenantApply($request->getUserId());
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 用户申请加入租户
     * @param Request $request
     * @return \think\Response
     */
    public function applyAppendToTenant(Request $request)
    {
        try {
            $param = $request->param();
            $reData = $this->tenantService->applyAppendToTenant($request->getUserId(), $param['data']['tenant_id'], $param['data']['reasons']);
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 同意用户加入租户
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function agreeAppendUserToTenant(Request $request)
    {
        try {
            $param = $request->param();
            $reData = $this->tenantService->agreeAppendUserToTenant($param['data']);
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 拒绝用户加入租户
     * @param Request $request
     * @return \think\Response
     */
    public function refuseAppendUserToTenant(Request $request)
    {
        try {
            $param = $request->param();
            $reData = $this->tenantService->refuseAppendUserToTenant($param['data']['tenant_apply_id']);
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询指定租户申请用户信息
     * @param Request $request
     * @return \think\Response
     */
    public function getTenantApplyUserList(Request $request)
    {
        $param = $request->param();
        $reData = $this->tenantService->getTenantApplyUserList($param['param']['filter']['tenant_id']);
        return json(success_response('', $reData));
    }

    /**
     * 查询租户详情  (包含认证信息 认证等级)
     * @param Request $request
     * @return \think\Response
     */
    public function getTenantDetail(Request $request)
    {
        $param = $request->param();
        $reData = $this->tenantService->getTenantDetail($param['param']['filter']['tenant_id']);
        return json(success_response('', $reData));
    }

    /**
     * 更新用户部门信息
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function saveUserDepartment(Request $request)
    {
        $param = $request->param()['param'];
        $data = $request->param()['data'];
        // data是数组 需要循环验证
        $validate = new Tenant();
        $validate->scene('SaveUserDepartmentItem');
        foreach ($data as $departmentData) {
            if (!$validate->check($departmentData)) {
                throw_strack_exception("data[]." . $validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
            }
        }
        try {
            $reData = $this->tenantService->saveUserDepartment($param['filter']['tenant_id'], $param['filter']['user_id'], $data);
            return json(success_response('', $reData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询用户部门工序id列表
     * @param Request $request
     * @return \think\Response
     */
    public function getUserDepartmentStepIdList(Request $request)
    {
        $param = $request->param()['param'] ?? [];
        $userId = $param['user_id'] ?? $request->getUserId();
        $tenantId = $param['tenant_id'] ?? $request->getTenantId();
        $roleIdList = $param['role_id_list'] ?? [];
        $res = $this->tenantService->getUserDepartmentStepIdList($userId, $tenantId, $roleIdList);
        return json(success_response('OK', $res));
    }

    /**
     * 设置用户职位
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function setUserPosition(Request $request)
    {
        $data = $request->param()['data'];
        $userIdList = $data['user_id_list'];
        $tenantId = isset($data['tenant_id']) && $data['tenant_id'] > 0 ? $data['tenant_id'] : $request->getTenantId();
        $tenantPositionId = $data['tenant_position_id'] ?? '';

        try {
            $res = $this->tenantService->setUserPosition($userIdList, $tenantId, $tenantPositionId);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 导入用户岗位
     */
    public function importUserPosition(Request $request)
    {
        $data = $request->param()['data'];
        $userPositionList = $data['user_position_list'] ?? [];
        $tenantId = isset($data['tenant_id']) && $data['tenant_id'] > 0 ? $data['tenant_id'] : $request->getTenantId();

        try {
            $res = $this->tenantService->importUserPosition($userPositionList, $tenantId);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取租户部门成员
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function selectDepartmentUserDepartmentInfoMerged(Request $request)
    {
        $param = $request->param();
        if (!isset($param['param']['filter']['tenant_id'])
            || (is_numeric($param['param']['filter']['tenant_id']) && $param['param']['filter']['tenant_id'] <= 0)) {
            $param['param']['filter']['tenant_id'] = $request->getTenantId();
        }
        if (!empty($param['param']['filter']['unset_tenant_id'])) {
            unset($param['param']['filter']['tenant_id']);
            unset($param['param']['filter']['unset_tenant_id']);
        }
        $includeEmployed = $param['param']['include_employed'] ?? 'no';
        $resData = $this->tenantService->selectDepartmentUserDepartmentInfoMerged($param['param'], $includeEmployed === 'yes');
        return json(success_response('', $resData));
    }

    /**
     * 租户部门人员角色存在检查
     * @param Request $request
     * @return \think\Response
     */
    public function checkDepartmentUserExist(Request $request)
    {
        $param = $request->param();
        if (!isset($param['param']['filter']['tenant_id']) || $param['param']['filter']['tenant_id'] <= 0) {
            $param['param']['filter']['tenant_user.tenant_id'] = $request->getTenantId();
        } else if (!empty($param['param']['filter']['tenant_id'])) {
            $param['param']['filter']['tenant_user.tenant_id'] = $param['param']['filter']['tenant_id'];
        }
        $resData = $this->tenantService->checkDepartmentUserExist($param['param']);
        return json(success_response('', $resData));
    }

    /**
     * 获取当前租户的基本信息
     * @param Request $request
     * @return \think\Response
     */
    public function getCurrentTenantInfo(Request $request)
    {
        $resData = $this->tenantService->getCurrentTenantInfo($request->getTenantId());
        return json(success_response('', $resData));
    }

    /**
     * 查询乙方权限
     * @return \think\Response
     */
    public function selectToTenantRole()
    {
        $resData = $this->tenantService->selectToTenantRole();
        return json(success_response('', $resData));
    }

    /**
     * 设置乙方权限
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function setToTenantRole(Request $request)
    {
        $param = $request->param();
        $resData = $this->tenantService->setToTenantRole($param['data']);
        return json(success_response('', $resData));
    }

    /**
     * 获取工单归属有关的租户信息
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function getWorkOrderRelatedTenant(Request $request)
    {
        $param = $request->param();
        $resData = $this->tenantService->getWorkOrderRelatedTenant($param['param'], $request->getTenantId());
        return json(success_response('', $resData));
    }

    /**
     * 创建团队
     * @param Request $request
     * @return \think\Response
     * @throws \Exception|\Throwable
     */
    public function registerTenant(Request $request)
    {
        try {
            $resData = $this->tenantService->registerTenant($request->getUserId(), $request->param());
            return json(success_response('OK', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 删除团队
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function deleteTenant(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->tenantService->deleteTenant($param['param']['filter']);
            return json(success_response('OK', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 解散团队
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function disband(Request $request)
    {
        try {
            $param = $request->param();
            $this->tenantService->disband($request->getUserId(), $param['data']);
            return json(success_response('OK'));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 更新团队信息
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function updateBaseInfo(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->tenantService->updateBaseInfo($param['data']);
            return json(success_response('OK', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 更新团队信息(服务类别、法人信息)
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function updateInfo(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->tenantService->updateInfo($param['data']);
            return json(success_response('OK', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }
}
